package com.tz.farmer.filter;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.smartPark.msframe.enums.BizRetCode;
import com.smartPark.msframe.result.ResultEx;
import com.tz.farmer.config.RedisConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;


/**
 * @version V1.0
 * @description: 过滤器
 * @name LoginCheckFilter
 * @author: xuhj
 * @date: 2020/7/3
 */
@Component
public class PermissionCheckFilter implements Filter {
    /**
     * 相关日志
     */
    Logger logger = LoggerFactory.getLogger(this.getClass());


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException, NullPointerException {
        ResultEx resultEx = new ResultEx();

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpRequest.setCharacterEncoding("UTF-8");
        httpResponse.setCharacterEncoding("UTF-8");

        String requestUri = httpRequest.getRequestURI();
        String ctxPath = httpRequest.getContextPath();
        String url = requestUri.substring(ctxPath.length());


        boolean isFilter = false;
        if (url.equals("/login/in")
                || url.contains("swagger")
                || url.contains("api-docs")
        ) {
            isFilter = true;
        } else {
            String userToken = httpRequest.getHeader("token");

            if (userToken != null && !("").equals(userToken)) {
                Jedis jedis = null;
                try {
                    jedis = RedisConfig.getJedis();
                    if (jedis != null) {
                        //延长过期时间
                        jedis.expire(userToken, 3600);
                        String userIdAndUserName = jedis.get(userToken);
                        if (!"".equals(userIdAndUserName) && userIdAndUserName != null) {
                            isFilter = true;
                        } else {
                            resultEx.setRetCode(BizRetCode.NOT_LOGIN_ERROR.getCode());
                            resultEx.setRetMsg("该用户已过期，请重新登陆！");
                            resultEx.setData(null);
                        }
                    } else {
                        resultEx.setRetCode(BizRetCode.FAILED.getCode());
                        resultEx.setRetMsg("jedis获取失败！");
                        resultEx.setData(null);
                    }

                } catch (Exception e) {
                    resultEx.setRetCode(BizRetCode.FAILED.getCode());
                    resultEx.setRetMsg(e.getMessage());
                    resultEx.setData(null);
                } finally {
                    if (jedis != null) {
                        RedisConfig.returnJedis(jedis);
                    }
                }
            } else {
                resultEx.setRetCode(BizRetCode.FAILED.getCode());
                resultEx.setRetMsg("token未传,请传入token参数");
                resultEx.setData(null);
            }
        }
        if (resultEx.getRetCode() != null) {// 验证失败
            PrintWriter writer = null;
            OutputStreamWriter osw = null;
            try {
                osw = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
                writer = new PrintWriter(osw, true);
                String jsonStr = JSONObject.toJSONString(resultEx, SerializerFeature.WriteMapNullValue);
                writer.write(jsonStr);
                writer.flush();
            } catch (UnsupportedEncodingException e) {
                logger.error("过滤器返回信息失败:" + e.getMessage(), e);
            } catch (IOException e) {
                logger.error("过滤器返回信息失败:" + e.getMessage(), e);
            } finally {
                if (null != writer) {
                    writer.close();
                }
                if (null != osw) {
                    osw.close();
                }
            }
            return;
        }
        if (isFilter) {
            try {
                filterChain.doFilter(httpRequest, httpResponse);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("权限放行失败:", e);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
